package com.wp.file.controller;


import com.wp.file.common.BaseContext;
import com.wp.file.common.R;
import com.wp.file.pojo.File;
import com.wp.file.pojo.User;
import com.wp.file.pojo.Warehouse;
import com.wp.file.service.FileService;
import com.wp.file.service.UserService;
import com.wp.file.service.WarehouseService;
import com.wp.file.utils.FileSort;
import com.wp.file.utils.FileUtil;

import com.wp.file.utils.FtpHelper;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletResponse;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件的基本操作 增删改查
 */
@Slf4j
@RestController
@RequestMapping("/api/file")
public class FileController {
    @Autowired
    private FileService fileService;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private UserService userService;


    @PostMapping("/upload")
    public R<String> uploadFile(@RequestParam("files") MultipartFile[] files, String path,@RequestParam("md5s") String[] fileMd5s) {
        for (int i = 0; i < files.length; i++) {
            //上传文件并保存
            boolean saveFlag = fileService.saveFile(files[i], path, fileMd5s[i]);
            if(!saveFlag){
                //上传失败时
                return R.error("文件上传失败!");
            }
        }
        return R.success("文件上传成功!");
    }

    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response,@RequestParam("id") Long warehouseId){
        //先查到这个文件的信息
        Warehouse warehouse = warehouseService.getById(warehouseId);
        File file = fileService.getById(warehouse.getFileId());
        response.setCharacterEncoding("utf-8");
        // 设置返回类型
        response.setContentType("multipart/form-data");
        OutputStream os = null;
        try {
            os = new BufferedOutputStream(response.getOutputStream());
            // 文件名转码一下，不然会出现中文乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(warehouse.getDisplayName(), "UTF-8"));
            boolean downloadFlag = FtpHelper.downloadFile(os, file.getPath(), file.getStorename(), warehouse.getDisplayName());
            if(downloadFlag){
                log.info("文件下载成功!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(os);
        }

    }


}



